//
//  LoginViewController.m
//  ios
//
//  Created by mac on 11-11-12.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "ASIHTTPRequest.h"
#import "SBJson.h"
#import <CommonCrypto/CommonDigest.h>



@implementation LoginViewController
@synthesize nameTextFidld;
@synthesize codeTextField;
@synthesize checkTextField;
@synthesize myView;


/*************************这里是当键盘挡住textfield的时候控制界面的上移***********************/
//此处还有个bug～！～！～！～！
- (void)moveView:(UITextField *)textField leaveView:(BOOL)leave  
{  
    
        UIView *accessoryView = textField.inputAccessoryView;//inputview是增加再默认键盘的上面
        UIView *inputview     = textField.inputView;  //这个如果有就会代替掉默认键盘。
        
        float textFieldY = 0;  
        float accessoryY = 0;  

    if (accessoryView && inputview)   
        {  
            CGRect accessoryRect = accessoryView.frame;  
            CGRect inputViewRect = inputview.frame;  
            accessoryY = 480 - (accessoryRect.size.height + inputViewRect.size.height);  
        }  
        else if (accessoryView)  
        {  
            CGRect accessoryRect = accessoryView.frame;  
            accessoryY = 480 - (accessoryRect.size.height + 216);  
        }  
        else if (inputview)  
        { 
            CGRect inputViewRect = inputview.frame;  
            accessoryY = 480 -inputViewRect.size.height;  
        }  
        else  
        { 
            accessoryY = 264; //480 - 216; 默认键盘高度为216 
        }  
        
        
        CGRect textFieldRect = textField.frame;  
        textFieldY = textFieldRect.origin.y + textFieldRect.size.height+20+myView.frame.origin.y;//前面的值如果按460算就不需要这个20（前提是view。  
        float offsetY = textFieldY - accessoryY; 
        if (!leave && offsetY > 0)   
        {  
            float y_offset = -5;  //这个控制textfield跟键盘的距离
            
            y_offset += -offsetY;  
            
            CGRect viewFrame = self.view.frame;  
            
            viewFrame.origin.y += y_offset;  
            
            [UIView beginAnimations:nil context:NULL];  
            [UIView setAnimationBeginsFromCurrentState:YES];  
            [UIView setAnimationDuration:0.3]; //这个时间刚刚好，再少就会出现脱节现象 
            [self.view setFrame:viewFrame];  
            [UIView commitAnimations];  
        }  
        else  //这个不能少，否则滚上去的图片没法退回来
        {  
            CGRect viewFrame = CGRectMake(0, defaultY, 320, 480); //这里的y为0，有时候为20或其他值，具体情况由视图控制器的view的原来的y值决定；可以在.h文件中定义一个成员变量，在viewdidload中将视图控制器的view的原始y值赋给这个成员变量。
            
            [UIView beginAnimations:nil context:NULL];  
            [UIView setAnimationBeginsFromCurrentState:YES];  
            [UIView setAnimationDuration:0.3];  
            [self.view setFrame:viewFrame];  
            [UIView commitAnimations];  
        }  

    }  

- (void)textFieldDidBeginEditing:(UITextField *)textField  
{  
        [self moveView:textField leaveView:NO];  
}  

- (void)textFieldDidEndEditing:(UITextField *)textField;  
{  
    [self moveView:textField leaveView:YES];  
}
/*************************这里是当键盘挡住textfield的时候控制界面的上移***********************/








/************************让弹出的软键盘退出***********************/
-(IBAction)touchBackground:(id)sender
{
    [nameTextFidld resignFirstResponder];
    [codeTextField resignFirstResponder];
    [checkTextField resignFirstResponder];
}

-(IBAction)retunkeyTouchDown:(id)sender
{
    [sender resignFirstResponder];
}
/*************************让弹出的软键盘退出***********************/






/************************SBJson数据解析***********************/
//使用SBJson的步骤如下
//1 下载SBJson解析包；
//2 将SBJson解析包的classes导入xcode中（注意不能只是将classes复制到项目所在的文件夹）
//3 #import "SBJson.h"
//4将json字符串转为NSDictionary对象,如下所示：

-(void)visitDict:(NSDictionary *)dict
{  
    NSDictionary *dic1=[dict objectForKey:@"responseData"];
     NSNumber *loginstr=[dic1 objectForKey:@"loginstate"];//这个时候ture已经不是bool值了，而是nsnumber
    int login=[loginstr intValue];
    if(login ==1)
    {
        [self.view removeFromSuperview];
    }
        
    else
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Login Faild" message:@"Please try it again!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}
/*************************SBJson数据解析***********************/






/*************************将密码进行MD5加密处理***********************/
//计算hashcode
-(NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];//这里可以选择32，40等其他整数，最终返回的是从开始往后依次输出不能随意选。
    CC_MD5( cStr, strlen(cStr), result );
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}//如果想输出16位，将后面的八个resulut元素去掉就行，一个字符占8位，而％02x将这个字符的二进制表示的前后四位分别用16进制数输出（4位二进制可以表达一个16进制数）

/*************************将密码进行MD5加密处理***********************/






/*************************登陆系统***********************/
-(void)logintemp:(id)sender
{
    [self.view removeFromSuperview];
}


-(void)login:(id)sender
{
    NSString *hashString=[NSString stringWithFormat:@"%@",[self md5:codeTextField.text]];
    NSString *loginString=[NSString stringWithFormat:@"http://txw.monca.cn:8080/rest.aspx?act=Customer.login&LoginName=%@&LoginPass=%@&CheckCode=gsy8",nameTextFidld.text,hashString];
    NSURL *url=[NSURL URLWithString:loginString];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
	[request setDelegate:self];
	[request startAsynchronous];
    [request setDidFinishSelector:@selector(requestDone:)];
	[request setDidFailSelector:@selector(requestWrong:)];
    [super viewDidLoad];
}



-(void) requestDone:(ASIHTTPRequest *)request
{
    NSString *responseString = [request responseString];
    NSLog(@"fanhuijieguo:%@",responseString);
    NSDictionary *items = [responseString JSONValue]; 
    [self visitDict:items];
}

-(void) requestWrong:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}

/*************************登陆系统***********************/











- (void)viewDidLoad
{
   
    defaultY=self.view.frame.origin.y;
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [nameTextFidld release];
    [codeTextField release];
    [checkTextField release];
    [myView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    //
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end






